﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public class headtest : MonoBehaviour {

	// Use this for initialization
	void Start () {
		
	}
	
	// Update is called once per frame
	void Update () {
		
	}

    public RawImage Mytexture;
    public RawImage TestImg;
    public Button testBtn;

    IEnumerator LoadTexture(string name)
    {
        //注解1 
        string path = "file:///" + Application.persistentDataPath + "/" + name;
        string path1 = Application.persistentDataPath + "/" + name;

        Debug.Log("LoadTexture path==>" + path);
        WWW www = new WWW(path);
        while (!www.isDone) { }
        Mytexture = GameObject.Find("Headimages").GetComponent<RawImage>();
        yield return www;
        //ImageStart(path1);
        Mytexture.texture = www.texture;

        StartCoroutine(DoScreenShot(Mytexture.gameObject));
    }



    public void TestBtnClick()
    {

        StartCoroutine(DoScreenShot(Mytexture.gameObject));
    }



    IEnumerator DoScreenShot(GameObject obj)
    {
        GameObject camera = GameObject.FindWithTag("MainCamera");
        Vector3 vex = camera.GetComponent<Camera>().WorldToScreenPoint(obj.transform.position);
        Rect rect = new Rect(vex.x/300, vex.y/300, 800, 800);
        Debug.Log(vex.x);
        Debug.Log(vex.y);
        /*
        创建Rect对象，在cocos2d里的参数left和Top是截取点距离屏幕左边和顶部的距离，但我这样赋值的时候报错了，后来发现在unity3d里，left和Top就是起始点的坐标x和y，也就是距离左边和下边的距离，width和height是一样的，截取的范围，这里需要注意，这个坐标一定要转换成屏幕坐标，在NGUI是这样转换的

        UICamera.currentCamera.WorldToScreenPoint(MaskTop.transform.position)

        没用NGUI的话直接用Camera对象转换即可

        */
        //创建截屏纹理


        Texture2D screenShot = new Texture2D((int)rect.width, (int)rect.height, TextureFormat.RGB24, false);

        TestImg.texture = screenShot;

        yield return new WaitForEndOfFrame();

        //截图并保存为纹理

        screenShot.ReadPixels(rect, 0, 0);

        screenShot.Apply();

        //转换成字节流并保存在本地

        byte[] bytes = screenShot.EncodeToJPG();

        
        //需要显示就用WWW加载显示

        //然后把这个字节流上传到服务器就行啦
    }
}
